package ctm.javacode;

import java.io.* ; 
import java.util.*;
import java.sql.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/editPw.do")

public class editPw extends HttpServlet {

	private final String SUCCESS_VIEW = "main.jsp"; 
	private final String ERROR_VIEW = "editPwError.jsp"; 
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		String nextpage = ERROR_VIEW;
		String name = (String) session.getAttribute("login");
		String oldpw = request.getParameter("pw");
		String pw = request.getParameter("newpw");
		String repw = request.getParameter("renewpw");
		
		List<String> errors = new ArrayList<String>() ;
			
		if (isInvalidPW( pw ))
			errors.add("密碼無效");
		if ( ! pw.equals(repw))
			errors.add("密碼不一致");
		
		if ( errors.isEmpty() ) {
			nextpage = SUCCESS_VIEW ;
			try {
				if ( !updateUserAndTestUesrPW( oldpw, pw,name ) ) {
					errors.add("密碼錯誤或無更動");
					nextpage = ERROR_VIEW ;
					request.setAttribute("errors", errors) ;
				} // end if
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} // end if
		else {
			request.setAttribute("errors", errors) ;
		} // end else
			
	
		request.getRequestDispatcher(nextpage)
		   .forward(request, response);		
	} // end doPost

	private boolean updateUserAndTestUesrPW(String oldpw, String pw, String name) throws NamingException, SQLException {
		dbBean db = new dbBean( "jdbc/ctmpllab" );
		String sqlQuery_testPW = "SELECT PASSWORD FROM accounttable WHERE ACCOUNT = '" + name + "'" ;
		pw = md5Encrypt.generate(pw);//用md5加密帳戶密碼
		
		String sqlQuery_updatePW = "UPDATE accounttable SET PASSWORD = '" + pw + "' WHERE ACCOUNT = '" + name + "'" ;
		oldpw = md5Encrypt.generate(oldpw);//用md5加密帳戶密碼

		
		db.Connected();
		ResultSet rs = db.ExcuteQuery(sqlQuery_testPW); ;
		rs.next(); 
		if ( ! rs.getString("password").trim().equals(oldpw) )
			return false ;
		if (  rs.getString("password").trim().equals(pw) )
			return false ;
		
		if ( pw != null && ! pw.equals("") )	
			db.ExcuteUpdate( sqlQuery_updatePW );
		
		
		return true;
	}

	private boolean isInvalidPW(String pw) {
		return pw.equals("") || ( pw.length() < 6 || pw.length() > 12 ) ;
	}
	
	
} // end class
